<template>
  <v-sprite
    @click="handleClick"
    ref="sprite"
    @transformend="handleTransformEnd"
    :config="{ ...config, image: image }"
  >
  </v-sprite>
</template>
<script>

export default {
  name: 'XSprite',
  props: {
    config: {
      type: Object
    }
  },
  mounted () {
    this.setImage(this.config.src);
  },
  methods: {
    handleTransformEnd (...p) {
      this.$emit('transformend', ...p)
    },
    setImage (src) {
      const image = new window.Image();
      image.src = src;
      image.onload = () => {
        // set image only when it is loaded
        this.image = image;
      };
    },
    handleClick () {
      const node = this.$refs.sprite.getNode();
      if (node.isRunning()) {
        node.stop();
      } else {
        node.start();
      }
    }
  },
  data () {
    return {
      image: null
    };
  },
  watch: {
    "config.src": {
      async handler (newSrc) {
        console.log(newSrc, 'newSrc');
        this.setImage(newSrc);
      }
    }
  }

}
</script>
